use axum::{extract::Query, http::StatusCode, response::IntoResponse};
use axum_extra::extract::Multipart;
use serde::Deserialize;
use serde_json::json;

use crate::services;

pub async fn index() -> impl IntoResponse {
    super::shared::get_data_response(json!({
      "name": "file"
    }))
}

#[derive(Debug, Deserialize)]
pub struct UploadParam {
    id: String,
}

/// If you encounter error: `Result::unwrap()` on an `Err` value: MultipartError { source: failed to read stream }
/// Just check DefaultBodyLimit value setting in lib.rs.
pub async fn upload(
    Query(params): Query<UploadParam>,
    mut multipart: Multipart,
) -> impl IntoResponse {
    while let Some(field) = match multipart.next_field().await {
        Ok(field) => field,
        Err(_) => {
            return StatusCode::NOT_ACCEPTABLE;
        }
    } {
        let filename = field.file_name().unwrap().to_string();
        let data = field.bytes().await.unwrap();
        services::file_service::save_upload(&filename, &data);
    }

    println!("id value: {}", params.id);

    StatusCode::NO_CONTENT
}
